<?php
namespace hid\storages\db;

use hid\base\IdBuilder;
use hid\base\IdStorage;
use Exception;
use PDO;
use PDOException;

/**
 * mysql db id存储器
 *<B>说明：</B>
 *<pre>
 * 略
 *</pre>
 */
class DbStorage extends IdStorage
{
    /**
     * PDO 对象
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     * @var PDO
     */
    protected $conn = null;

    protected $dsn = '';

    protected $username = '';

    protected $password = '';

    /**
     * 连接redis 服务
     *<B>说明：</B>
     *<pre>
     *  创建Redis实例
     *</pre>
     * @return PDO
     * @throws Exception
     */
    protected function getConnection():PDO
    {
        if (is_null($this->conn)) {
            try {
                //创建pdo 数据库连接
                $this->conn = new PDO($this->dsn, $this->username, $this->password);
            } catch (PDOException $e) {
                throw new Exception($e->getMessage());
            }
        }

        return $this->conn;
    }

    public function setInitValue(IdBuilder $idBuilder,int $value = 0):bool
    {
        return true;
    }

    public function incrBy(IdBuilder $idBuilder,int $step = 1):?int
    {
        $table = $idBuilder->getStoreKey();
        $sql = 'replace into ' . $table . ' (stub) values(\'a\')';

        $conn = $this->getConnection();
        $result = $conn->prepare($sql)->execute();
        if ($result === true) {
            return (int)$this->conn->lastInsertId();
        } else {
            return null;
        }
    }



}
